package com.cloudcms.web.handler;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cloudcms.web.common.BusinessException;
import com.cloudcms.web.entity.Admin;
import com.cloudcms.web.annotation.SessionAdmin;
import com.cloudcms.web.base.redis.session.template.RedisSessionTemplate;
import com.cloudcms.web.util.Constants;
import com.cloudcms.web.util.CommUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * 
 * @author lisjie
 *
 */
@Service
public class SessionAdminHandler implements HandlerMethodArgumentResolver {

	@Autowired
	private RedisSessionTemplate redisSessionTemplate;

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		// 如果参数类型是Admin并且有SessionAdmin注解则支持
		if (parameter.getParameterType().isAssignableFrom(Admin.class)
				&& parameter.hasParameterAnnotation(SessionAdmin.class)) {
			return true;
		}
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		SessionAdmin info = parameter.getParameterAnnotation(SessionAdmin.class);
		/* 由客户端传递登录信息 */
		if (info != null) {
			HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
			HttpServletResponse response = (HttpServletResponse) webRequest.getNativeResponse();

			Cookie[] cookies = request.getCookies();

			String sessionid = "";
			if (cookies != null && cookies.length > 0) {
				for (Cookie c : cookies) {
					if (Constants.COOKIEPREFIX.equals(c.getName())) {
						sessionid = c.getValue();
						break;
					}
				}
			}

			if (StringUtils.isEmpty(sessionid)) {
				sessionid = CommUtil.generateToken(request);

				Cookie cookie = new Cookie(Constants.COOKIEPREFIX, sessionid);
				cookie.setPath("/");
				cookie.setHttpOnly(true);

				response.addCookie(cookie);
			}
			Admin admin = redisSessionTemplate.getAttribute(Constants.SESSIONPREFIX + sessionid, "login_admin", Admin.class);

			if(admin == null||admin.getUsername()==null||"".equals(admin.getUsername())) {
				throw new BusinessException(Constants.NOT_LOGIN_IN,"客户未登录或登录已过期");
			}
			redisSessionTemplate.setAttribute(Constants.SESSIONPREFIX+sessionid,"login_admin",admin);
			return admin;
		} else {
			throw new BusinessException(Constants.NOT_LOGIN_IN,"请登录后操作");
		}
	}
}
